# coding=utf-8
from django.shortcuts import render, redirect, get_object_or_404
from django.http import JsonResponse
from .models import User, Star
from wechat.utils import *
from wechat.conf import *
import requests
import random
import re

# Create your views here.

def get_user(request, id):
    user = get_object_or_404(User, pk=id)
    if user is None:
        return JsonResponse({'code': 404, 'message': 'Not Found'})
    return JsonResponse({'code': 0, 'user': user})


def upload(request):
    # if request.method == 'GET':
    #     # try:
    #     #     open_id = request.GET['openid']
    #     # except KeyError:
    #     #     return 'invalid url'
    #     config = get_jsapi_signature("%s%s" % (SITE_DOMAIN, request.get_full_path()))
    #     if config is None:
    #         return 'server busy, try again'
    #     #render('upload.html', {'openId': open_id, 'config': config})
    #     return render(request, 'upload.html', {'config': config})
    if request.method == 'POST':
        data = request.POST
        try:
            file_id = data['fileId']
            name = data['name']
            phone = data['phone']
        except KeyError:
            return JsonResponse({'code': 500, 'message': 'server busy, try again'})
        p = re.compile('^0\d{2,3}\d{7,8}$|^1[358]\d{9}$|^147\d{8}$')
        match = p.match(phone)
        if not match:
            return JsonResponse({'code': 403, 'message': '错误电话号码'})
        #open_id = data['openId']
        access_token = get_access_token()
        if access_token is None:
            return JsonResponse({'code': 501, 'message': 'server busy, try again'})
        try:
            r = requests.get("http://file.api.weixin.qq.com/cgi-bin/media/get" +
                             "?access_token=%s&media_id=%s" % (access_token, file_id))
        except:
            return JsonResponse({'code': 502, 'message': 'server busy, try again'})
        file_type = r.headers['Content-type'].split('/')[1]
        file_path = save_image(file_type, 'upload/user', r.content)
        #User.objects.create(wechat_openid=open_id, picture_path=file_path)
        try:
            star = random.choice(Star.objects.all())
        except:
            star = Star.objects.create(name="star")
        user = User.objects.create(picture_path=file_path, star=star, name=name, phone=phone)
        return JsonResponse({'code': 0, 'result': {'id': user.id, 'photo': user.picture_path}})


def get_fake_data(request):
    data = get_data()
    return JsonResponse({'code': 0, 'result': data})


